<?php  defined('SYSPATH') OR die('No direct access allowed.');

/**
 *质检操作的类方法
 * @package  qualityaction
 * @author   hzr
 */
class  qualityaction
{


    /**
     * 质检报表查询

     */
    public static function selectquality($where,$limit = '',$order = '')
    {

        $fields = 'id,invoice_date,purchaseorder_id,check_man,supplier_id,sku,sku_name,print_status,pur_evidence';

        if(empty($order)){
            $order = ' ';
        }else{
            $order = ' ORDER BY '.$order.' asc';
        }
        if(empty($limit)){
            $limit = ' ';
        }else{
            $limit = ' LIMIT '.$limit;
        }
        $select_sql = "SELECT $fields FROM check_quality_details WHERE ".$where.$order.$limit;
        $res        = DB::query(Database::SELECT,$select_sql)
            ->execute('newerp')
            ->as_array();
        return $res;
    }


    // 以采购单为一组的质检报告
    public static function selectquality2($where,$limit = '',$order = '')
    {
        $result = array();
        $fields = 'DISTINCT(purchaseorder_id)';
        if(empty($order)){
            $order = ' ';
        }else{
            $order = ' ORDER BY '.$order.' ASC';
        }
        if(empty($limit)){
            $limit = ' LIMIT 0,100';
        }else{
            $limit = ' LIMIT '.$limit;
        }
        $select_sql = "SELECT $fields FROM check_quality_details WHERE ".$where.$order.$limit;
        $res        = DB::query(Database::SELECT,$select_sql)
            ->execute('newerp')
            ->as_array();

        foreach($res as $key => $value){
            $wh = '';
            $wh .= $where.' AND purchaseorder_id = '.$value['purchaseorder_id'].' AND fail_deal_way!=5';
            $result[$value['purchaseorder_id']] = self::selectquality($wh,'','invoice_date');
        }
        return $result;
    }

    //质检SQL语句 WHERE条件
    public static function qualitysql($data)
    {
        $dfrom      = isset($data['date_from'])?trim($data['date_from']):'';
        $dto        = isset($data['date_to'])?trim($data['date_to']):'';
        $purchaseid = isset($data['purchaseid'])?trim($data['purchaseid']):'';
        $status     = isset($data['status'])?trim($data['status']):'';
        $where      = '1=1';
        if(!empty($dfrom)&&!empty($dto)){
            $where .= " AND invoice_date >= '".$dfrom." 00:00:00' AND invoice_date <= '".$dto." 23:59:59'";
        }
        if(!empty($purchaseid)){
            $where .= " AND purchaseorder_id = '".$purchaseid."'";
        }
        if($status!='all'){
            $where .= " AND print_status = ".$status;
        }
        //合格量为0的质检数据不展示
        $where .= " AND qualified_quantity!=0";
        //让步接收的不展示
        $where .= " AND fail_deal_way!=5";
        return $where;
    }

    // 获取合格质检表总条数
    public static function qualitycount($where)
    {
        $select_sql = "SELECT COUNT(0) AS count FROM check_quality_details WHERE ".$where;
        $count      = DB::query(Database::SELECT,$select_sql)
            ->execute('newerp')
            ->as_array();
        if(empty($count)){
            return 0;
        }else{
            return $count[0]['count'];
        }
    }

    // 获取以采购为主的总条数
    public static function qualitycount2($where)
    {
        $select_sql = "SELECT COUNT(DISTINCT(purchaseorder_id)) AS count FROM check_quality_details WHERE ".$where;
        $count      = DB::query(Database::SELECT,$select_sql)
            ->execute('newerp')
            ->as_array();
        if(empty($count)){
            return 0;
        }else{
            return $count[0]['count'];
        }
    }

    // 插入不良品信息
    public static function insertunquality($data)
    {
        //print_r($data);
        $warehouse_id             = Kohana::$config->get('warehouse')->warehouse_id;
        $addarr                   = array();
        $addarr['sku']            = trim($data['sku']);
        $addarr['sku']            = strtoupper($addarr['sku']);
        $addarr['sku_name']       = trim($data['sku_name']);
        $addarr['sku_name']       = trim($addarr['sku_name']);
        $addarr['quantity']       = trim($data['sku_quality']);
        $addarr['quality_man']    = USER::Active_user()->id;
        $addarr['quality_remark'] = trim($data['remarks']).',手动录入不良品入库单';
        $addarr['invoice_date']   = date('Y-m-d H:i:s',time());
        $addarr['check_time']     = date('Y-m-d H:i:s',time());
        $addarr['warehouseid']    = $warehouse_id;

        if(!empty($data['sku_unit'])){
            $addarr['sku_standard'] = trim($data['sku_unit']);
        }
        if(!empty($data['pur_name'])){
            $pur_name = trim($data['pur_name']);
            $pur_name = Erpuser::lookup_by_nick($pur_name);
            if(!empty($pur_name)){
                $addarr['purchase_man'] = $pur_name;
            }
        }
        //print_r($addarr);exit;
        if(!empty($addarr)){
            $id = DB::insert('unqualified_deal_invoices',array_keys($addarr))
                ->values($addarr)
                ->execute('newerp');
            return $id[0];
        }else{
            return 0;
        }
    }

    // 插入不良品出库信息
    public static function insertdelivery($data)
    {
        $warehouse_id        = Kohana::$config->get('warehouse')->warehouse_id;
        $info                = array();
        $info['sku']         = isset($data['sku'])?trim($data['sku']):'';
        $info['sku_name']    = isset($data['sku_name'])?trim($data['sku_name']):'';
        $info['quantity']    = isset($data['sku_quality'])?trim($data['sku_quality']):'';
        $info['warehouseid'] = $warehouse_id;

        if(!empty($data['sku_unit'])){
            $addarr['sku_standard'] = trim($data['sku_unit']);
        }
        $id = 0;
        if(!empty($addarr)){
            $id = DB::insert('bad_product_delivery',array_keys($info))
                ->values($info)
                ->execute('newerp');
        }
        return $id;
    }

    //查询质检报告
    public static function qualityinfo($where,$fields = '')
    {
        if(empty($fields)){
            $fields = 'purchaseorder_id,sku,sku_name,check_quantity,check_man,qualified_quantity,unquality_count,remark,pur_evidence';
        }
        $select_sql = 'SELECT '.$fields.' FROM check_quality_details WHERE '.$where.' order by invoice_date asc';
        $result     = DB::query(Database::SELECT,$select_sql)
            ->execute('newerp')
            ->as_array();
        return $result;
    }

    /**
     * 修改表
     * $set 为字符串
     */
    public static function updatequality($set,$where,$table)
    {
        $pur_query = "UPDATE ".$table." SET ".$set." WHERE ".$where;
        $id        = DB::query(Database::UPDATE,$pur_query)
            ->execute('newerp');
        return $id;
    }

    // 获取不良品处理方式
    public static function getunqualitymethod()
    {
        $sql = "SELECT `number`,`value` FROM `statusdics` WHERE `table`='unqualified_deal_invoices' AND `colum_name`='fail_deal_way'";
        $res = DB::query(Database::SELECT,$sql)
            ->execute('newerp')
            ->as_array();
        return $res;
    }


    // 获取不良品处理状态
    public static function getstatus()
    {
        $sql = "SELECT `number`,`value` FROM `statusdics` WHERE `table`='unqualified_deal_invoices' AND `colum_name`='status'";
        $res = DB::query(Database::SELECT,$sql)
            ->execute('newerp')
            ->as_array();
        return $res;
    }

    // 查询不良品信息
    public static function selecunqulity($where,$limit = '',$order = '')
    {
        $fields = 'id,check_detail_id,quality_man,purchaseorder_id,sku,sku_name,supplier,quality_remark,purchase_man,quantity,status,check_time';

        if(empty($order)){
            $order = ' ORDER BY id DESC';
        }else{
            $order = ' ORDER BY '.$order.' DESC';
        }
        if(empty($limit)){
            $limit = ' ';
        }else{
            $limit = ' LIMIT '.$limit;
        }
        $select_sql = "SELECT $fields FROM unqualified_deal_invoices WHERE ".$where.$order.$limit;

        $res = DB::query(Database::SELECT,$select_sql)
            ->execute('newerp')
            ->as_array();
        return $res;
    }

    //不良品表SQL语句 WHERE条件
    public static function unqualitysql($data)
    {
        $dfrom      = isset($data['date_from'])?trim($data['date_from']):'';
        $dto        = isset($data['date_to'])?trim($data['date_to']):'';
        $purchaseid = isset($data['purchaseid'])?trim($data['purchaseid']):'';
        $status     = isset($data['status'])?trim($data['status']):'';
        if(!empty($data['suppliername'])){
            $supplierid = isset($data['supplierid'])&&!empty($data['suppliername'])?trim($data['supplierid']):-1;
        }
        $sku        = isset($data['sku'])?trim($data['sku']):'';
        $checkid    = isset($data['checkid'])?trim($data['checkid']):'';
        $purid      = isset($data['purid'])?trim($data['purid']):'';
        //		$id = trim($data['id']);//页面没有传过来id 注释掉,下边有三行也注释掉
        $where = '1=1';
        if(isset($data['no_purchaseorder_id']) && $data['no_purchaseorder_id'] != 0) {
            $where .= " AND purchaseorder_id " . ($data['no_purchaseorder_id'] == 10 ? '=' : '>') . '0';
        }
        if(!empty($dfrom)&&!empty($dto)){
            $where .= " AND check_time >= '".$dfrom." 00:00:00' AND check_time <= '".$dto." 23:59:59'";
        }
        if(!empty($purchaseid)){
            $where .= " AND purchaseorder_id = ".$purchaseid;
        }
        if(!empty($status)){
            $where .= " AND status = ".$status;
        }
        if(!empty($sku)){
            $where .= " AND sku = '".$sku."'";
        }
        if(!empty($checkid)){
            if($checkid==1){
                $where .= ' AND quality_man = 1';
            }else{
                $where .= ' AND quality_man = '.$checkid;
            }
        }
        if(!empty($purid)){
            $where .= ' AND purchase_man = '.$purid;
        }

        if(!empty($supplierid)){
            if($supplierid==1){
                $where .= " AND supplier IN (1)";
            }else{
                $where .= " AND supplier IN (".$supplierid.")";
            }
        }

        //		if(!empty($id)){
        //			$where .= " AND id = ".$id;
        //		}
        return $where;
    }

    public static function selone($id,$fields = '')
    {
        if(empty($fields)){
            $fields = 'sku,sku_name,quantity,quality_remark';
        }
        $select_sql = "SELECT $fields FROM unqualified_deal_invoices WHERE id=".$id;
        $res        = DB::query(Database::SELECT,$select_sql)
            ->execute('newerp')
            ->as_array();
        return $res;
    }

    // 获取不合格质检表总条数
    public static function unqualitycount($where)
    {
        $select_sql = "SELECT COUNT(0) AS count FROM unqualified_deal_invoices WHERE ".$where;
        $count      = DB::query(Database::SELECT,$select_sql)
            ->execute('newerp')
            ->as_array();
        if(empty($count)){
            return 0;
        }else{
            return $count[0]['count'];
        }
    }

    // 获取用户ID
    public static function getuserid($checkid)
    {

        $select_sql = "SELECT id FROM users WHERE nick = '".$checkid."'";
        $res        = DB::query(Database::SELECT,$select_sql)
            ->execute()
            ->as_array();
        if(empty($res)){
            return 0;
        }else{
            return $res['0']['id'];
        }
    }

    // 获取用户名称
    public static function getusername($id)
    {
        $select_sql = "SELECT nick FROM users WHERE id = '".$id."'";
        $res        = DB::query(Database::SELECT,$select_sql)
            ->execute()
            ->as_array();
        if(empty($res)){
            return 0;
        }else{
            return $res['0']['nick'];
        }
    }

    // 获取计划员ID
    public static function getpurchaseid($id)
    {
        $select_sql = "SELECT purchase_id FROM purchaseorders WHERE id = '".$id."'";
        $res        = DB::query(Database::SELECT,$select_sql)
            ->execute('newerp')
            ->as_array();
        if(empty($res)){
            return 0;
        }else{
            return $res['0']['purchase_id'];
        }
    }

    // 获取供应商ID
    public static function getsupplierid($supplierid)
    {
        if(!empty($supplierid)){
            //START--------------------------------CWY--------------------------------------------------------
            $res = Newerpclientapi::getSuppliers(array('id'),array('name' => "like '%$supplierid%'"));
            //			$select_sql = "SELECT id FROM erp_provider WHERE vProviderName like '%".$supplierid."%'";
            //			$res = DB::query(Database::SELECT,$select_sql)->execute('readonlyerp')->as_array();
            //END----------------------------------CWY--------------------------------------------------------
            return $res;
        }else{
            return array();
        }
    }

    // 获取供应商名称
    public static function getsuppliername($supplierid)
    {
        //START--------------------------------CWY--------------------------------------------------------
        $res = supplierskus::getSuppliers(array('name'),array('id' => "=$supplierid"));
        if(empty($res)){
            return 0;
        }else{
            return $res['0']['name'];
        }
        //        $select_sql = "SELECT vProviderName FROM erp_provider WHERE id =".$supplierid;
        //        $res        = DB::query(Database::SELECT,$select_sql)
        //            ->execute('readonlyerp')
        //            ->as_array();
        //        if(empty($res)){
        //            return 0;
        //        }else{
        //            return $res['0']['vProviderName'];
        //        }
        //END--------------------------------CWY--------------------------------------------------------
    }

    // 获取sku信息
    public static function getskuname($sku,$fields = '')
    {
        if(empty($fields)){
            $fields = 'products_name_cn,oper';
        }
        $sku = trim($sku);
        //START--------------------------------CWY--------------------------------------------------------
        $skus = Skusystemapi::getSku($sku);
        if(empty($skus)){
            return 0;
        }else{
            $cnname                  = Skusystemapi::getSkuCnname($sku);
            $usersku                 = Skusystemapi::getUserSku($sku);
            $res['products_name_cn'] = $cnname[0]['name'];
            $res['oper']             = isset($usersku[0]['user_id'])?$usersku[0]['user_id']:'';
            return $res;
        }
        //        $select_sql = "SELECT $fields FROM erp_products_data WHERE products_sku ='".$sku."'";
        //        $res        = DB::query(Database::SELECT,$select_sql)
        //            ->execute('readonlyerp')
        //            ->as_array();
        //        if(empty($res)){
        //            return 0;
        //        }else{
        //            return $res['0'];
        //        }
        //END--------------------------------CWY--------------------------------------------------------
    }

    // 获取erp系统采购人名称
    public static function geterpname($userid)
    {
        if(empty($fields)){
            $fields = 'name';
        }
        $userid = trim($userid);
        //START--------------------------------CWY--------------------------------------------------------
        $res = Skusystemapi::getUserNick($userid);
        if(empty($res)){
            return 0;
        }else{
            return $res['nick'];
        }
        //        $select_sql = "SELECT $fields FROM erp_manages WHERE id ='".$userid."'";
        //        $res        = DB::query(Database::SELECT,$select_sql)
        //            ->execute('readonlyerp')
        //            ->as_array();
        //        if(empty($res)){
        //            return 0;
        //        }else{
        //            return $res['0']['name'];
        //        }
        //END--------------------------------CWY--------------------------------------------------------
    }

    // 操作员的动作日志记录
    public static function insertlog($data)
    {
        $data['log_time'] = date('Y-m-d H:i:s');
        $data['userid']   = USER::Active_user()->id;
        $id               = DB::insert('erp_logs',array_keys($data))
            ->values($data)
            ->execute('newerp');
    }

    public static function getQualitymen($quality_men_id){
        !empty($quality_men_id)&&$quality_men=DB::select('id','nick')->from('users')->where('id','in',$quality_men_id)->execute('default')->as_array('id','nick');
        return !empty($quality_men_id)?$quality_men:null;

    }
}
